from flask import Blueprint,jsonify,request
from utils.comm import get_data,xtree
from db import db1
import datetime


bp_organization = Blueprint('organization',__name__)


@bp_organization.route('/organizationlist',methods=['GET','POST'])
def organizationlist():
    sql = "select id,name,pid from organization "
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})



@bp_organization.route('/deptlist',methods=['GET','POST'])
def deptlist():
    if request.method == 'POST':
        data = request.json

        sql = "select id from dept where coding='%s'"% data['coding']
        res = db1.find(sql)
        time = datetime.datetime.strftime(datetime.datetime.now(), '%y-%m-%d')
        sql1 = "insert into dept (name,coding,pid,starttime) values ('%s','%s',%d,'%s')"%(data['name'],data['code'],int(res['id']),time)
        db1.update(sql1)
        return jsonify({'code':200,'msg':'ok'})

    else:
        sql = "select id,name,coding,pid from dept"
        res = db1.find_all(sql)
        data = xtree(res)
        return jsonify({'code': 200, 'list': data})


@bp_organization.route('/getposts',methods=['POST','GET'])
def getposts():
    if request.method == 'POST':
        data = request.json
        sql = "update posts set name='%s',describe='%s',dept_id='%s' where id=%d"%(data['name'],data['describe'],data['dept_id'],int(data['id']))
        db1.update(sql)
        return jsonify({'code':200})
    else:
        test = request.args.get('test')
        if test:
            sql = "select * from posts where name like '%s'" % test
        else:
            sql = "select * from posts"
        res = db1.find_all(sql)
        return jsonify({'code': 200, 'data': res})

@bp_organization.route('/getdutys',methods=['POST','GET'])
def getdutys():
    if request.method == 'POST':
        data = request.json
        sql = "update dutys set name='%s',code='%s' where id=%d"%(data['name'],data['code'],int(data['id']))
        db1.update(sql)
        return jsonify({'code':200})
    else:
        test = request.args.get('test')
        if test:
            sql = "select * from dutys where name like '%s'" % test
        else:
            sql = "select * from dutys"
        res = db1.find_all(sql)
        return jsonify({'code': 200, 'data': res})



